/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reyes.mysite.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import reyes.mysite.jdo.Blog;
import reyes.mysite.dao.GenericDAO;

/**
 *
 * @author reyesyang
 */
public class SaveBlogEditAction extends org.apache.struts.action.Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        String id = request.getParameter("blogId");
        String title = request.getParameter("blogTitle");
        String category = request.getParameter("blogCategory");
        String privacy = request.getParameter("blogPrivacy");
        String summary = request.getParameter("blogSummary");
        String content = request.getParameter("blogContent");

        GenericDAO<Blog> blogDAO = new GenericDAO<Blog>();

        blogDAO.beginTransaction();
        try {
            Blog blog = blogDAO.getById(Blog.class, Long.valueOf(id));
            blog.setTitle(title);
            blog.setNickTitle(title.replace(' ', '-').toLowerCase());
            blog.setCategory(category);
            blog.setPrivacy(privacy);
            blog.setSummary(summary);
            blog.setContent(content);

            request.setAttribute("blog", blog);
            blogDAO.commitTransaction();
        } catch (Exception e) {
            System.out.println("Can't update blog, Detail: " + e.getMessage());
        } finally {
            if(blogDAO.isActiveTransaction()) {
                blogDAO.rollbackTransaction();
            }
            blogDAO.closePM();
        }

        return mapping.findForward("blogDetails");
    }
}
